TextEditor = {
    name = "TextEditor",
    dependencies = {
        FocusArea,
        HoverArea,
    }
}
TextEvent = RegisterEvents{
    "TextChanged"
}
function TextEditor:ctor()
end

function TextEditor:backspace()
    local str = self.label.string
    if string.len(str) > 0 then
        local byteoffset = utf8.offset(str, -1)
        if byteoffset then
            self.label.string = string.sub(str, 1, byteoffset - 1)
        end
    end
end

function TextEditor:input(str)
    self.label.string = self.label.string..str
    self:emit(TextEvent.TextChanged, self.label.string)
end

function TextEditor:setWithoutNotify(str)
    self.label.string = str
end

function Node.TextEditor(textName, str)
    local node = Node.Layout():wh(200, 25)
    node.layoutType = LayoutType.Horizontal
    node.layoutSizeMode = LayoutSizeMode.StretchX
    node:axy(0, 0)
    node.name = "textEditor"
    node:addComponent(TextEditor)
    node:addComponent(SwitchButton)

    local content = node
    if str == nil then
        str = textName
    else
        local textName = Node.Label(textName):addTo(node)
        node.textName = textName
    end

    local bg = Node.Scale9("roundedBox48"):wh(200, 25)
    bg.name = "textEditorBg"
    bg:addTo(content)
    bg.interactable = false

    local border = Node.Scale9("roundedBorder48"):addComponent(Stretch):addTo(bg)
    border.name = "border"
    border.interactable = false
    border.style = Styles.buttonLabel
    border.styleTarget = node
    border.touchSwallowed = false

    local label = Node.Label(str):addComponent(Align):addTo(bg)
    label.ax = 0
    label.alignPercentX = 0
    label.alignOffsetX = 5
    label.interactable = false
    label.touchSwallowed = false
    node.label = label
    return node, label
end